<?php Workerman\Protocols\Http::sessionStart(); $G_MODEL_NAME = basename(__FILE__,'.js.php'); $G_MODEL_URL = $_SESSION["MES_WEB_URL"].'/'. $G_MODEL_NAME; ?>
<?php $access_token = $_SESSION["ACCESS_TOKEN"];?>

//右上角菜单按键
$(".mod_btn_<?php echo $G_MODEL_NAME; ?>").on("click", function(e){
	mod_fun_action($(this).attr("data-tap"));
	return;
});


$('#<?php echo $G_MODEL_NAME; ?>_form').validate({
	submitHandler:function(form){  


		var action = "";
		if($('[name="mod_input_id"]').val()==""){
			//如果ID为空，新建一个记录
			action = "add";
		}else{
			//ID不为空，保存旧记录
			action = "edit";
		}
		ajax_request({url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{
            action:action,
			id:$('[name="mod_input_id"]').val(),
			name:$('[name="mod_input_name"]').val(),
			code:$('[name="mod_input_code"]').val(),
			note:$('[name="mod_input_note"]').val()
        },access_token:"<?php echo $access_token?>"},function(result){
            var result = JSON.parse(result);
            result = result["rtval"];
            if(result=="done"){
                //刷新数据
                oTable.ajax.reload();
                $('#dlg_<?php echo $G_MODEL_NAME; ?>_form').modal('hide');
            }else{
                alert(result);
            }
        })
		return false;
	},
	 rules: {
		 mod_input_name: {
			required: true,
			minlength: 1,
			remote:{
				url: "<?php echo $G_MODEL_URL;?>",     //后台处理程序  
				type: "post",               //数据发送方式  
				dataType: "json",		  //接受数据格式 
				async: true, 
				beforeSend: function (request) {
					request.setRequestHeader("access_token","<?php echo $access_token?>");
				},
				data: {                      //要传递的数据
					id:         function() {return $('[name="mod_input_id"]').val()},
					data:    function() {return $('[name="mod_input_name"]').val();},
					action:  function() {return 'check_name';},
				}
			}
		 },
		 mod_input_code: {
			 required: true,
			 minlength: 1,
			remote:{
				url: "<?php echo $G_MODEL_URL;?>",     //后台处理程序  
				type: "post",               //数据发送方式  
				dataType: "json",		  //接受数据格式 
				async: true, 
				beforeSend: function (request) {
					request.setRequestHeader("access_token","<?php echo $access_token?>");
				},
				data: {                      //要传递的数据
					id:         function() {return $('[name="mod_input_id"]').val()},
					data:    function() {return $('[name="mod_input_code"]').val();},
					action:  function() {return 'check_code';},
				}
			}
		 }
	 }
});

function mod_fun_action(key){
	
	if(key=="add"){
		$('[name="mod_input_id"]').val("");
		$('[name="mod_input_name"]').val("");
		$('[name="mod_input_code"]').val("");
		$('[name="mod_input_note"]').val("");
		$('#dlg_<?php echo $G_MODEL_NAME; ?>_form').modal('show');
		return;
	}
	
	if(key=="edit"){
		var o = oTable.row('.selected');
		//判断没有选中行
		if(typeof(o.data()) == "undefined"){
			return;
		}
		$('[name="mod_input_id"]').val(o.data()[0]);
		$('[name="mod_input_name"]').val(o.data()[1]);
		$('[name="mod_input_code"]').val(o.data()[2]);
		$('[name="mod_input_note"]').val(o.data()[3]);
		$('#dlg_<?php echo $G_MODEL_NAME; ?>_form').modal('show');
		return;
	}
	
	if(key=="delete"){
		var o = oTable.row('.selected');
		//判断没有选中行
		if(typeof(o.data()) == "undefined"){
			return;
		}
		swal({ 
          title: '确定删除该记录', 
          text: '如果删除该记录,数据将无法恢复!', 
          type: 'warning',
          showCancelButton: true, 
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          confirmButtonText: '删除！',
          cancelButtonText: '取消！', 
        }).then(function(result){
            if (result.value) {
                //删除当前选择行
				var id = o.data()[0];
				ajax_request({url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{action:"delete",id:id},access_token:"<?php echo $access_token?>"},function(result){
                    var result = JSON.parse(result);
                    result = result["rtval"];
                    if(result=="done"){
                        //刷新数据
                        oTable.ajax.reload();
                        swal(
                            '已经删除!',
                            '该记录已被成功删除',
                            'success'
                        );
                    }else{
                        oTable.ajax.reload();
                        swal(
                            '无法删除!',
                            result,
                            'error'
                        );
                        
                    }
                })
            } 
        })			
		return;
	}
	
	if(key=="refresh"){
		//刷新数据
		oTable.ajax.reload();
		return;
	}
	
	return;
}

//创建右键菜单
function doDynamicMenu(idx, pos) {
	var $mymenu = $("<div class='mod_menu_<?php echo $G_MODEL_NAME; ?>'/>");
	$("body").append($mymenu);
	$.contextMenu({
		selector: '.mod_menu_<?php echo $G_MODEL_NAME; ?>',
		callback: function(key, options) {
			mod_fun_action(key);
		},
		items: {
			"add": {
				name: "添加",
				className: 'mod_menu_btn_<?php echo $G_MODEL_NAME; ?>_cps_001'
			},
			"edit": {
				name: "修改",
				className: 'mod_menu_btn_<?php echo $G_MODEL_NAME; ?>_cps_002'
			},
			"delete": {
				name: "删除",
				className: 'mod_menu_btn_<?php echo $G_MODEL_NAME; ?>_cps_003'
			},
			"sep1": "---------",
			"refresh": {
				name: "刷新",
				className: 'mod_menu_btn_<?php echo $G_MODEL_NAME; ?>_cps_004'
			}
		}

	});
	$(".mod_menu_<?php echo $G_MODEL_NAME; ?>").contextMenu(pos);
}

var oTable = $('#<?php echo $G_MODEL_NAME; ?>_list').DataTable({
	"ajax": {
        url:"<?php echo $G_MODEL_URL;?>",
        beforeSend: function (request) {
            request.setRequestHeader("access_token","<?php echo $access_token?>");
        },
        "dataSrc": function ( json ) {
			check_ajax_request(json);
            return json["rtval"]["data"];
        }
    },
	"deferRender": true,
	"fnInitComplete": function() {
		//数据读取完成事件
	},

	"oLanguage": {
		"sLengthMenu": "每页显示 _MENU_ 条记录",
		"sZeroRecords": "抱歉， 没有找到",
		"sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
		"sInfoEmpty": "没有数据",
		"sInfoFiltered": "(从 _MAX_ 条数据中检索)",
		"sZeroRecords": "没有检索到数据",
		"sSearch": "搜索:",
		"oPaginate": {
			"sFirst": "首页",
			"sPrevious": "前一页",
			"sNext": "后一页",
			"sLast": "尾页"
		}
	},

	"fnRowCallback": function(nRow) {
		$(nRow).on('mousedown',
		function(e) {
			if (e.button == 2) {
				if ($(this).hasClass('selected')) {
					//$(this).removeClass('selected');
				} else {
					oTable.$('tr.selected').removeClass('selected');
					$(this).addClass('selected');
				}
				
				doDynamicMenu(0, {
					x: e.clientX + document.documentElement.scrollLeft - document.documentElement.clientLeft + 5,
					y: e.clientY + document.documentElement.scrollTop - document.documentElement.clientTop
				});
				return false;
			} else {
				
				if ($(this).hasClass('selected')) {
					//$(this).removeClass('selected');
				} else {
					oTable.$('tr.selected').removeClass('selected');
					$(this).addClass('selected');
				}
			}
			return true;
		});
	},
	dom: '<"html5buttons"B>lTfgitp',
	buttons: [{
		extend: 'copy'
	},
	{
		extend: 'csv'
	},
	{
		extend: 'excel',
		title: 'ExcelFile'
	},
	{
		extend: 'pdf',
		title: 'PDFFile'
	},

	{
		extend: 'print',
		customize: function(win) {
			$(win.document.body).addClass('white-bg');
			$(win.document.body).css('font-size', '10px');

			$(win.document.body).find('table').addClass('compact').css('font-size', 'inherit');
		}
	}]

});
